package cn.dev.mybatis.config;

import cn.dev.mybatis.core.SqlSession;
import cn.dev.mybatis.core.SqlSessionFactory;
import cn.dev.mybatis.db.DefaultDatasource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class MyBatisAutoConfiguration {
    @Bean
    @ConditionalOnBean(DataSourceProperties.class)
    @ConditionalOnMissingBean(DataSource.class)
    public DataSource dataSource(DataSourceProperties dataSourceProperties) {
        DefaultDatasource defaultDatasource = new DefaultDatasource();
        defaultDatasource.setDriver(dataSourceProperties.getDriverClassName());
        defaultDatasource.setUrl(dataSourceProperties.getUrl());
        defaultDatasource.setUsername(dataSourceProperties.getUsername());
        defaultDatasource.setUsername(dataSourceProperties.getPassword());
        return defaultDatasource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactory();
        sqlSessionFactory.setDataSource(dataSource);
        return sqlSessionFactory;
    }

    @Bean
    @ConditionalOnBean(SqlSessionFactory.class)
    public SqlSession sqlSession (SqlSessionFactory sqlSessionFactory) {
        return sqlSessionFactory.openSession(true);
    }
}
